<?php
namespace framework\core;
use framework\dao\PDODAO;
class Model{
    protected $dao;
    protected $true_table;
    protected $error=array();
    protected $pk_list=array();
    public function getError(){
        $str='';
        foreach ($this->error as $k=>$v){
            $str.=$v.'<br/>';
        }
        return $str;
    }
    public function __construct()
    {
        $this->initDao();
        $this->initTable();
        $this->initField();
    }
    private function initTable(){
        $this->true_table='`'.$this->login_table.'`';
    }
    private function initField(){
        $sql="desc $this->true_table";
        $field_list=$this->dao->fetchAll($sql);
        foreach ($field_list as $k=>$v) {
            if ($v['Key']=='PRI'){
                $this->pk_list['pk']=$v['Field'];
            }
        }
    }
    private function initDao(){
        $config=$GLOBALS['config'];
        $this->dao=PDODAO::getSingleInstance($config);
    }
    public function insert($data){
        $sql="INSERT INTO $this->true_table";
        $keys=array_keys($data);
        $field=array_map(function ($v){
            return '`'.$v.'`';
        },$keys);
        $str=implode(',',$field);
        $sql.="(".$str.")";

        $value=array_values($data);
        $values=array_map(array($this->dao,'quote'),$value);
        $values=implode(',',$values);
        $sql.="VALUES(".$values.")";
        $this->dao->query($sql);
        return $this->dao->insertId();
    }
    public function delete($id){
        $sql="DELETE FROM $this->true_table WHERE {$this->pk_list['pk']}=$id";
        return $this->dao->query($sql);
    }
    public  function update($data,$where){
        if (!is_null($where)){
            foreach ($where as $k=>$v){
                $where_str='`'.$k.'`'."='$v'";
            }
        }else{
            return false;
        }
        $sql="UPDATE $this->true_table SET";
        foreach ($data as $k=>$v) {
            $arr[]='`'.$k.'`'."='$v'";
        }
        $field=implode(",",$arr);
        $sql.=$field."WHERE".$where_str;
        return $this->dao->query($sql);
    }
    public function select($data,$where=null){
        if(is_null($where)){
            $sql="SELECT * FROM $this->true_table ";
            return $this->dao->fetchAll($sql);
        }else{
            $field=array_map(function($v){
                return '`'.$v.'`';
            },$data);
            $str=implode(',',$field);
            foreach ($where as $k=>$v){
                $where_str='`'.$k.'`'."='$v'";
            }
            $sql="SELECT $str FROM $this->true_table WHERE $where_str";
            return $this->dao->fetchRow($sql);
        }
    }
}